<template>
    <div>
        <el-dialog
            width="1200px"
            title="选择人员"
            :visible.sync="dialogVisible"
            @close="getAuthor"
            :before-close="handleCloseDialog"
            @open="getAuthor"
        >
            <div class="container">
                <div class="total part">
                    <div class="title">
                        <p>所有人员</p>
                    </div>
                    <div class="content container columnLayout">
                        <div class="total-left left-container">
                            <el-tree
                                node-key="id"
                                :data="data"
                                :props="defaultProps"
                                :default-expanded-keys="expanded"
                                :expand-on-click-node="false"
                                @node-click="userList($event)"
                                @node-expand="handleNodeExpand"
                                @node-collapse="handleNodeCollapse"
                            >
                                <section class="custom-tree-node" slot-scope="{ node, data }">
                                    <section style="width: 100px">{{ node.label }}</section>
                                </section>
                            </el-tree>
                        </div>
                        <div class="total-table right-container">
                            <div class="dialogSearch">
                                <el-input
                                    v-model="inputName"
                                    placeholder="请输入人员"
                                    @input="userList1($event, inputName)"
                                >
                                    <!--                                          @input=" getList2 ($event,true)"-->
                                    <i slot="suffix" class="el-input__icon el-icon-search"></i>
                                </el-input>
                                <el-table
                                    v-loading="loading"
                                    :data="allStaffData"
                                    stripe
                                    border
                                    empty-text="暂无数据"
                                    ref="allStaffData"
                                    style="margin-top: 10px"
                                    @select="handleSelect"
                                    @select-all="handleSelect"
                                    @selection-change="handleSelectionChange"
                                    :row-key="getRowKeys"
                                    :header-cell-style="{
                    'background-color': '#eeeeee !important',
                  }"
                                >
                                    <el-table-column
                                        type="index"
                                        label="序号"
                                        width="60"
                                        align="center"
                                    >
                                        <template slot-scope="scope">
                      <span>{{
                              (page.pageNo - 1) * page.pageSize + scope.$index + 1
                          }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="name"
                                        label="姓名"
                                        min-width="99"
                                    ></el-table-column>
                                    <el-table-column
                                        prop="office.name"
                                        label="部门"
                                        min-width="99"
                                    ></el-table-column>

                                    <!--S test-->
                                    <el-table-column
                                        prop="id"
                                        label="id"
                                        min-width="99"
                                    ></el-table-column>
                                    <el-table-column
                                        label="isChedked"
                                        min-width="99"
                                    >
                                    <template slot-scope="scope">
                      <span>{{scope.row.isChedked}}</span>
                                        </template>
                                    </el-table-column>
                                    <!--E test-->



                                    <el-table-column
                                        type="selection"
                                        :reserve-selection="true"
                                        width="50"
                                    >
                                    </el-table-column>
                                </el-table>
                                <div class="select-group-bottom">
                                    <el-pagination
                                        @current-change="handleCurrentChange"
                                        :current-page.sync="page.pageNo"
                                        :page-size="page.pageSize"
                                        background
                                        layout="total, prev, pager, next"
                                        :total="page.total"
                                    >
                                    </el-pagination>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="selected part">
                    <div class="title">
                        <p>已选人员</p>
                    </div>
                    <div class="selected-content">
                        <el-tag
                            v-for="(tag, index) in selectedStaff"
                            :key="index"
                            @close="handleClose(tag)"
                            closable
                        >
                            {{ tag.name }}
                        </el-tag>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick
        >确定</el-button
        >
        <el-button size="small" @click="close()">取消</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
import { treeData, userList, getAuthor, save } from '@/api/tenant/tenant.js'
import { getTreeData } from '@/api/market/product.js'
treeData
export default {
    name: 'staffForm',
    data () {
        return {
            department: { id: '' },
            dialogVisible: false,
            data: [],
            loading: false,
            expanded: [],
            allStaffData: [],
            inputName: '',
            page: {
                pageSize: 10,
                pageNo: 1,
                total: 0
            },
            selectedStaff: [],
            defaultProps: {
                // 修改el-tree默认data数组参数
                label: 'name',
                id: 'id',
                parentId: 'parentId',
                children: 'children'
            }
        }
    },
    computed: {
        // selectedStaff() {
        //   // 可以监听对象的单个属性
        //   return this.$store.state.tentant.use;
        //   // console.lov(val)
        // },
    },
    methods: {
    	handleCloseDialog(done){
    		this.$refs.allStaffData.clearSelection()
    		done();
    	},
    	handleSelect (selection, row) {
			let selectedStaff = this.selectedStaff,
				allStaffData = this.allStaffData
				// 清空当前列表在selectedStaff里所有（用于取消选择）
				allStaffData.forEach((v, i) => {
					selectedStaff.forEach((val, index) => {
						if (v.id == val.id) {
							// 去重
							selectedStaff.splice(index, 1)
						}
					})
				})
			this.selectedStaff = selectedStaff.concat(selection)
        },
        doSubmit () {
            let ids = []
            this.selectedStaff.forEach(item => {
                ids.push(item.id)
            })
            ids = ids.join(',')
            save({
                bookId: this.$store.state.tentant.bookAuthorDTO.bookAuthorDTO.bookId,
                useId: ids,
                id: this.$store.state.tentant.bookAuthorDTO.bookAuthorDTO.id

            }).then(res => {
                this.$message({
                message: '恭喜您编辑成功',
                type: 'success'
                })
                this.$emit('refreshDataList', this.selectedStaff)
            })
        },
        init () {
            this.dialogVisible = true
            this.getTreeData()
            // this.getAuthor();
            this.getInfo()
        },
        getInfo () {
            this.loading = true
            this.loading = false
        },
        // 分页
        handleCurrentChange (e) {
            this.page.pageNo = e
            console.log(this.department.id)
            this.userList(this.department)
        },
        userList ($event, inputName) {
            this.loading = true
            this.department = $event
//          console.log(this.$store.state.tentant.bookAuthorDTO)
            let that = this
            userList({
                departmentId: $event.id,
                useId: that.$store.state.tentant.bookAuthorDTO.bookAuthorDTO.useId,
                name: inputName,
                pageSize: this.page.pageSize,
                pageNo: this.page.pageNo
            }).then((res) => {
                if (res.data.code === '200') {
                    // this.$refs.allStaffData.clearSelection();
                    let list = res.data.result.list,
                    selectedStaff = this.selectedStaff
                    that.allStaffData = list
                    that.page.total = res.data.result.count
                    this.loading = false
                    this.$refs.allStaffData.clearSelection()
                    list.forEach((row, index) => {
                    	selectedStaff.forEach((v, i) => {
                    		if (v.id == row.id) {
                    			that.$refs.allStaffData.toggleRowSelection(row, true)
                    		}
                    	})
//                      if (row.isChedked == 1) {
//                      	console.log("添加选中项")
//                      	console.log(selectedStaff);
//                      	that.$refs.allStaffData.toggleRowSelection(row)
//                      	if(!selectedStaff.length){
//                      		return;
//                      	}
//                      	selectedStaff.forEach((v,i)=>{
//                      		if(v.id==row.id){
//                      			return;
//                      		}else{
//                      			that.$refs.allStaffData.toggleRowSelection(row)
//                      		}
//                      	})
//                      	that.$refs.allStaffData.toggleRowSelection(row)
//                          that.selectedStaff.forEach((item, index) => {
//                              if (item.id === row.id) {
//                                  console.log(111111111)
//                                  // that.selectedStaff.splice(index,1)
//
//                                  console.log(that.selectedStaff)
//                                  that.$refs.allStaffData.toggleRowSelection(row)
//                              }
//                          })
//                      }
                    })
                }
            })
            // this.getAuthor().then((res) => {

            //   userList({ departmentId: $event.id,useId:that.$store.state.tentant.bookAuthorDTO.bookAuthorDTO.useId, name: inputName,pageSize:this.page.pageSize,pageNo:this.page.pageNo }).then((res) => {
            //     if (res.data.code === "200") {
            //       this.$refs.allStaffData.clearSelection();
            //       that.allStaffData = res.data.result.list;
            //       that.page.total = res.data.result.count;

            //       that.allStaffData.forEach((row,index) => {
            //         console.log(index);
            //         console.log(row);
            //         if (row.isChedked==1) {
            //            that.$refs.allStaffData.toggleRowSelection(row);
            //         }

            //       });
            //       that.loading = false;
            //     }
            //   });
            // });
        },
        // 获取授权数据
        getAuthor () {
            let that1 = this
            return new Promise(function (resolve, reject) {
                that1.$store.state.tentant.bookAuthorDTO
                console.log(347, that1.$store.state.tentant.bookAuthorDTO.bookAuthorDTO)
                getAuthor({
                    useId: that1.$store.state.tentant.bookAuthorDTO.bookAuthorDTO.useId
                }).then((res) => {
                    that1.selectedStaff = res.data.page.userList

                    //
                    console.log(354, that1.selectedStaff)
                    resolve(res.data)
                })
            })
        },
        // 获得全部人员
        getStaff (page) {
            // let that = this
            // return new Promise(function (resolve, reject) {
            //     getCarList({ pageSize: page.pageSize, pageNo: page.pageNo }).then(
            //         (res) => {
            //             that.allCarData = res.data.result.list;
            //             that.page2.total = res.data.result.count;
            //             resolve(res.data.code);
            //         }
            //     )
            // })
        },
        getRowKeys (row) {
            return row.id
        },
        uniqueArr (array) {
            var n = [] // 结果数组
            // 从第一项开始遍历
            for (var i = 0; i < array.length; i++) {
                // 如果当前数组的第i项在当前数组中第一次出现的位置不是i，
                // 那么表示第i项是重复的，忽略掉。否则存入结果数组
                if (array.indexOf(array[i]) == i) n.push(array[i])
            }
            return n
        },

        // 关闭标签
        handleClose (tag) {
        	console.log(tag)
        	let list = this.allStaffData,
        	selectedStaff = this.selectedStaff
        	list.forEach((v, i) => {
        		if (v.id == tag.id) {
        			this.$refs.allStaffData.toggleRowSelection(tag, false)
        		}
        	})
        	selectedStaff.forEach((v, i) => {
        		if (v.id == tag.id) {
        			selectedStaff.splice(i, 1)
        		}
        	})
        	this.selectedStaff = selectedStaff
//          let selectedSyaffBuffer = JSON.parse(JSON.stringify(this.selectedStaff))
//          console.log(tag)
//          for (let i = 0; i < this.$store.state.tentant.use.length; i++) {
//              if (tag.id === this.$store.state.tentant.use[i].id) {
//                  console.log(i)
//                  selectedSyaffBuffer.splice(i, 1)
//                  this.$store.commit('tentant/setUse', selectedSyaffBuffer)
//                  break
//              }
//          }

            // this.$refs.allStaffData.toggleRowSelection(tag);
        },
        handleNodeExpand (data) {
            // 保存当前展开的节点
            let flag = false
            console.log(348)
            this.expanded.some((item) => {
                if (item === data.id) {
                    // 判断当前节点是否存在， 存在不做处理
                    flag = true
                    return true
                }
            })
            if (!flag) {
                // 不存在则存到数组里
                this.expanded.push(data.id)
            }
        },
        // 树节点关闭
        handleNodeCollapse (data) {
            // 删除当前关闭的节点
            this.expanded.some((item, i) => {
                if (item === data.id) {
                    this.expanded.splice(i, 1)
                }
            })
        },
        userList1 ($event, inputName) {
            this.loading = true
            console.log(inputName)

            userList({ name: inputName }).then((res) => {
                if (res.data.code === '200') {
                    this.allStaffData = res.data.result.list
                    this.page.total = res.data.result.count
                    console.log(this.allStaffData)

                    this.loading = false
                }
            })
        },

        getTreeData ($event) {
            treeData().then((res) => {
                if (res.data.code === 200) {
                    this.data = res.data.treeData
                }
            })
        },
        getList3 ($event, params) {
            console.log(params)
            getList({
                productCategoryId: $event.id,
                pageSize: params.pageSize,
                pageNo: params.pageNo
            }).then((res) => {
                if (res.data.code === '200') {
                    this.tableData = res.data.result.list
                    this.page.total = res.data.result.count
                    console.log(this.page.total)
                }
            })
        },
        close () {
            this.dialogVisible = false
        }
    },
    mounted () {}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
    .container {
        display: flex;
        .part {
            border: 1px solid #aaaaaa;
            padding: 15px;
            .title {
                margin-bottom: 10px;
            }
        }
        .part:first-child {
            margin-right: 20px;
        }
        .total {
            width: 80%;
            .content {
            }
        }
        .selected {
            width: calc(20% - 20px);
        }
    }
}
</style>
